/**
 * Copyright (C) 2006 OQube 
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *  
 * author: Arnaud Bailly - abailly AT oqube DOT com
 * created: 15 juin 2006
 */
package speculoos.jndi.mappers;

import java.util.Map;

import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;

import speculoos.core.Mapper;
import speculoos.core.MapperException;

/**
 * A mapper that constructs a list of replace modifications from an
 * {@see javax.naming.directory.Attributes}object. This object is intended for
 * use with {@see speculoos.jndi.mappers.AttributesFromInput} mapper that
 * transforms an input object into an Attributes object. IT transforms the
 * Attributes object into an array of
 * {@see javax.naming.directory.ModificationItem} objects with
 * <code>REPLACE</code> operation.
 * 
 * @author nono
 * 
 */
public class ModificationsFromAttributes implements Mapper {

	/*
	 * (non-Javadoc)
	 * 
	 * @see speculoos.core.Mapper#map(java.lang.Object, java.util.Map)
	 */
	public Object map(Object input, Map param) throws MapperException {
		try {
			Attributes attrs = (Attributes) input;
			int ln = attrs.size();
			ModificationItem[] mods = new ModificationItem[ln];
			int i = 0;
			for (NamingEnumeration ne = attrs.getAll(); ne.hasMore(); i++) {
				/* create mod item */
				mods[i] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
						(Attribute) ne.next());
			}
			return mods;
		} catch (ClassCastException e) {
			throw new MapperException(getName() + ": invalid type "
					+ input.getClass()
					+ ", expected javax.naming.directory.Attributes");
		} catch (NamingException e) {
			throw new MapperException(getName()
					+ ": error in retrieving attributes", e);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see speculoos.core.Mapper#getName()
	 */
	public String getName() {
		return "ModificationsFromAttributes";
	}

}
